import React, { useState, useEffect } from 'react';
import { AIConfig, MultiAIConfig, AIProvider } from '../types';

interface MultiAIConfigFormProps {
  config: MultiAIConfig;
  onChange: (config: MultiAIConfig) => void;
  availableApiKeys: Record<AIProvider, string>;
}

export const MultiAIConfigForm: React.FC<MultiAIConfigFormProps> = ({
  config,
  onChange,
  availableApiKeys
}) => {
  const [localConfig, setLocalConfig] = useState<MultiAIConfig>(config);

  useEffect(() => {
    setLocalConfig(config);
  }, [config]);

  const handleConfigChange = (newConfig: MultiAIConfig) => {
    setLocalConfig(newConfig);
    onChange(newConfig);
  };

  const getProviderDisplayName = (provider: AIProvider): string => {
    switch (provider) {
      case 'google':
        return 'Google AI (Gemini)';
      case 'deepseek':
        return 'DeepSeek';
      case 'tongyi':
        return '通义千问 (Qwen)';
      case 'doubao':
        return '豆包 (Doubao)';
      case 'wenxin':
        return '文心一言 (ERNIE)';
      default:
        return provider;
    }
  };

  const getDefaultModelForProvider = (provider: AIProvider): string => {
    const modelMap: Record<AIProvider, string> = {
      'google': 'gemini-pro',
      'deepseek': 'deepseek-reasoner',
      'tongyi': 'qwen-max-2025-01-25',
      'doubao': 'doubao-seed-1-6-250615',
      'wenxin': 'ernie-bot-turbo'
    };
    return modelMap[provider] || 'qwen-max-2025-01-25';
  };

  const addModel = () => {
    const defaultProvider: AIProvider = 'tongyi';
    const newModel: AIConfig = {
      provider: defaultProvider,
      apiKey: availableApiKeys[defaultProvider] || '',
      model: getDefaultModelForProvider(defaultProvider),
      temperature: 0.7,
      maxTokens: 2000,
      priority: localConfig.models.length + 1,
      enabled: true,
      maxRetries: 3
    };

    handleConfigChange({
      ...localConfig,
      models: [...localConfig.models, newModel]
    });
  };

  const removeModel = (index: number) => {
    const newModels = localConfig.models.filter((_, i) => i !== index);
    handleConfigChange({
      ...localConfig,
      models: newModels
    });
  };

  const updateModel = (index: number, updatedModel: AIConfig) => {
    const newModels = [...localConfig.models];
    newModels[index] = updatedModel;
    handleConfigChange({
      ...localConfig,
      models: newModels
    });
  };

  const moveModel = (index: number, direction: 'up' | 'down') => {
    const newModels = [...localConfig.models];
    const targetIndex = direction === 'up' ? index - 1 : index + 1;
    
    if (targetIndex >= 0 && targetIndex < newModels.length) {
      [newModels[index], newModels[targetIndex]] = [newModels[targetIndex], newModels[index]];
      
      // 更新优先级
      newModels.forEach((model, i) => {
        model.priority = i + 1;
      });
      
      handleConfigChange({
        ...localConfig,
        models: newModels
      });
    }
  };

  return (
    <div className="space-y-6">
      {/* 自动切换设置 */}
      <div className="bg-gradient-to-r from-blue-50 to-indigo-50 p-4 rounded-xl border border-blue-200">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-semibold text-gray-900 flex items-center space-x-2">
            <svg className="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
            <span>自动切换设置</span>
          </h3>
        </div>
        
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="flex items-center space-x-3">
            <input
              type="checkbox"
              id="autoSwitch"
              checked={localConfig.autoSwitch}
              onChange={(e) => handleConfigChange({
                ...localConfig,
                autoSwitch: e.target.checked
              })}
              className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500"
            />
            <label htmlFor="autoSwitch" className="text-sm font-medium text-gray-700">
              启用自动切换
            </label>
          </div>
          
          <div className="flex items-center space-x-3">
            <input
              type="checkbox"
              id="fallbackOnError"
              checked={localConfig.fallbackOnError}
              onChange={(e) => handleConfigChange({
                ...localConfig,
                fallbackOnError: e.target.checked
              })}
              className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500"
            />
            <label htmlFor="fallbackOnError" className="text-sm font-medium text-gray-700">
              错误时回退
            </label>
          </div>
          
          <div className="flex items-center space-x-3">
            <input
              type="checkbox"
              id="fallbackOnQuotaExhausted"
              checked={localConfig.fallbackOnQuotaExhausted}
              onChange={(e) => handleConfigChange({
                ...localConfig,
                fallbackOnQuotaExhausted: e.target.checked
              })}
              className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500"
            />
            <label htmlFor="fallbackOnQuotaExhausted" className="text-sm font-medium text-gray-700">
              配额耗尽时回退
            </label>
          </div>
        </div>
      </div>

      {/* 模型列表 */}
      <div>
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-semibold text-gray-900 flex items-center space-x-2">
            <svg className="w-5 h-5 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
            </svg>
            <span>AI模型配置</span>
          </h3>
          <button
            type="button"
            onClick={addModel}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center space-x-2"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
            <span>添加模型</span>
          </button>
        </div>

        <div className="space-y-4">
          {localConfig.models.map((model, index) => (
            <div key={index} className="bg-white p-4 rounded-xl border border-gray-200 shadow-sm">
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center space-x-3">
                  <span className="bg-blue-100 text-blue-800 text-xs font-medium px-2.5 py-0.5 rounded-full">
                    优先级 {model.priority}
                  </span>
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      checked={model.enabled !== false}
                      onChange={(e) => updateModel(index, {
                        ...model,
                        enabled: e.target.checked
                      })}
                      className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500"
                    />
                    <span className="text-sm font-medium text-gray-700">启用</span>
                  </div>
                </div>
                
                <div className="flex items-center space-x-2">
                  <button
                    type="button"
                    onClick={() => moveModel(index, 'up')}
                    disabled={index === 0}
                    className="p-1 text-gray-400 hover:text-gray-600 disabled:opacity-50"
                  >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 15l7-7 7 7" />
                    </svg>
                  </button>
                  <button
                    type="button"
                    onClick={() => moveModel(index, 'down')}
                    disabled={index === localConfig.models.length - 1}
                    className="p-1 text-gray-400 hover:text-gray-600 disabled:opacity-50"
                  >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                    </svg>
                  </button>
                  <button
                    type="button"
                    onClick={() => removeModel(index)}
                    className="p-1 text-red-400 hover:text-red-600"
                  >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                  </button>
                </div>
              </div>
              
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">提供商</label>
                  <select
                    value={model.provider}
                    onChange={(e) => {
                      const newProvider = e.target.value as AIProvider;
                      updateModel(index, {
                        ...model,
                        provider: newProvider,
                        apiKey: availableApiKeys[newProvider] || '',
                        model: getDefaultModelForProvider(newProvider)
                      });
                    }}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500"
                  >
                    <option value="tongyi">通义千问 (Qwen)</option>
                    <option value="doubao">豆包 (Doubao)</option>
                    {/* <option value="deepseek">DeepSeek</option> */}
                  </select>
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">模型</label>
                  <select
                    value={model.model}
                    onChange={(e) => updateModel(index, {
                      ...model,
                      model: e.target.value
                    })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500"
                  >
                    {model.provider === 'tongyi' && (
                      <>
                        <option value="qwen-max-2025-01-25">qwen-max-2025-01-25 (最新)</option>
                        <option value="qwen-max">qwen-max</option>
                        <option value="qwen-plus">qwen-plus</option>
                        <option value="qwen-turbo">qwen-turbo</option>
                        <option value="qwen-long">qwen-long</option>
                      </>
                    )}
                    {model.provider === 'doubao' && (
                      <>
                        <option value="doubao-seed-1-6-250615">doubao-seed-1-6-250615 (最新多模态)</option>
                        <option value="doubao-seed-1-6-flash-250715">doubao-seed-1-6-flash-250715 (快速版)</option>
                        <option value="doubao-seed-1-6-thinking-250715">doubao-seed-1-6-thinking-250715 (深度思考)</option>
                        <option value="doubao-1-5-thinking-vision-pro-250428">doubao-1-5-thinking-vision-pro-250428 (视觉推理)</option>
                        <option value="deepseek-r1-250528">deepseek-r1-250528 (深度推理)</option>
                      </>
                    )}
                    {model.provider === 'deepseek' && (
                      <>
                        <option value="deepseek-reasoner">deepseek-reasoner (R1推理模型)</option>
                        <option value="deepseek-chat">deepseek-chat (V3通用模型)</option>
                        <option value="deepseek-coder">deepseek-coder</option>
                      </>
                    )}
                  </select>
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">温度</label>
                  <input
                    type="number"
                    min="0"
                    max="2"
                    step="0.1"
                    value={model.temperature || 0.7}
                    onChange={(e) => updateModel(index, {
                      ...model,
                      temperature: parseFloat(e.target.value)
                    })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">最大重试次数</label>
                  <input
                    type="number"
                    min="1"
                    max="10"
                    value={model.maxRetries || 3}
                    onChange={(e) => updateModel(index, {
                      ...model,
                      maxRetries: parseInt(e.target.value)
                    })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
              </div>
              
              <div className="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">最大Token数</label>
                  <input
                    type="number"
                    min="100"
                    max="10000"
                    value={model.maxTokens || 2000}
                    onChange={(e) => updateModel(index, {
                      ...model,
                      maxTokens: parseInt(e.target.value)
                    })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">API密钥状态</label>
                  <div className="flex items-center space-x-2 px-3 py-2 bg-gray-50 rounded-lg">
                    {model.apiKey ? (
                      <>
                        <svg className="w-4 h-4 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                        </svg>
                        <span className="text-sm text-green-700">已配置</span>
                      </>
                    ) : (
                      <>
                        <svg className="w-4 h-4 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                        </svg>
                        <span className="text-sm text-red-700">未配置</span>
                      </>
                    )}
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
        
        {localConfig.models.length === 0 && (
          <div className="text-center py-8 text-gray-500">
            <svg className="w-12 h-12 mx-auto mb-4 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
            </svg>
            <p>暂无AI模型配置</p>
            <p className="text-sm mt-1">点击"添加模型"按钮开始配置</p>
          </div>
        )}
      </div>
    </div>
  );
};